<template>
  <div class="container">
    <el-row class="toolbar searchInputWidth" style="padding-bottom: 0">
      <el-form :inline="true" :model="filterField" ref="searchConditions">
        <el-col :lg="8" :xl="6">
          <el-form-item label="时间" class="row-padding-bottom">
            <el-date-picker
              v-model="filterField.time"
              type="date"
              placeholder="请选择"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :lg="8" :xl="6">
          <el-form-item label="专户账号" class="row-padding-bottom">
            <el-input
              v-model="filterField.searchText"
              placeholder="请输入专户账号"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <template v-if="advanced">
          <el-col :lg="8" :xl="6">
            <el-form-item label="类型" class="row-padding-bottom">
              <el-select
                v-model="filterField.operate"
                filterable
                placeholder="请选择类型"
                clearable
              >
                <el-option
                  v-for="item in typeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </template>
        <el-form-item>
          <a
            @click="toggleAdvanced"
            style="margin-left: 40px; color: #409eff; cursor: pointer"
            class="btnColor"
          >
            {{ advanced ? '收起' : '展开' }}
            <i
              :class="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
            ></i>
          </a>
          <el-button
            type="primary"
            icon="icon iconfont iconchazhao1"
            @click="searchList"
            class="searchBtn"
          >
            <span>搜索</span>
          </el-button>
          <!-- <el-button type="primary" @click="toExport()" class="commonBut  saveBtn funComBut" icon="icon iconfont icondaochu"  >
                      <span class="opetareText">导出</span>
                    </el-button> -->
        </el-form-item>
        <!-- <div style="display:inline-block" v-if="userType=='BANK' && bankAcountImport">
                    <div class="uploadBox">
                    <el-button round type="primary" class="createSalaryBut" @click = "isImport" v-if = "isShowImport == 1">导入</el-button>
                    <el-button round type="primary" class="createSalaryBut" v-if = "isShowImport == 0">导入</el-button>
                    <div class="upLoadDom"  v-if = "isShowImport == 0">
                        <form id="waterImportBox">
                        <input
                            type="file"
                            id="waterImportExcel"
                            name="multipartFile"
                            @change="waterImportfileChange"
                        />
                        </form>
                    </div>
                    <el-link type="primary" @click="downLoad()" class="uploadBtn">流水导入模板下载</el-link>
                    </div>
                </div> -->
      </el-form>
    </el-row>
    <div class="spacing"></div>
    <div
      ref="tableBox"
      :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
    >
      <div style="margin-bottom: 24px">
        <el-button
          type="primary"
          @click="toExport()"
          class="commonBut saveBtn funComBut"
          icon="icon iconfont icondaochu"
          style="margin-right: 8px"
        >
          <span class="opetareText">导出</span>
        </el-button>
        <div
          style="display: inline-block"
          v-if="userType == 'BANK' && bankAcountImport"
        >
          <div class="uploadBox">
            <el-button
              type="primary"
              class="commonBut saveBtn funComBut"
              icon="icon iconfont icondaoru"
              @click="isImport"
              v-if="isShowImport == 1"
              ><span class="opetareText">导入</span></el-button
            >
            <el-button
              type="primary"
              class="commonBut saveBtn funComBut"
              icon="icon iconfont icondaoru"
              v-if="isShowImport == 0"
              ><span class="opetareText">导入</span></el-button
            >
            <div class="upLoadDom" v-if="isShowImport == 0">
              <form id="waterImportBox">
                <input
                  type="file"
                  id="waterImportExcel"
                  name="multipartFile"
                  @change="waterImportfileChange"
                />
              </form>
            </div>
            <el-link
              type="primary"
              @click="downLoad()"
              class="uploadBtn"
              style="margin-left: 4px"
              >流水导入模板下载</el-link
            >
          </div>
        </div>
      </div>
      <el-table
        :data="salaryAccountList"
        v-loading="loading"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        highlight-current-row
        stripe
        ref="tableBox1"
        :max-height="tableHeight"
        style="border: 1px solid #dfe6ec"
      >
        <el-table-column
          prop="createTime"
          label="时间"
          align="center"
          :formatter="formatTd"
          width="175px"
        ></el-table-column>
        <el-table-column
          prop="journal"
          label="金额(元)"
          align="center"
          :formatter="formatTd"
        ></el-table-column>
        <el-table-column
          prop="operate"
          label="类型"
          align="center"
          :formatter="formatTd"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.operate == 'IN'">缴存</span>
            <span v-else>支出</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="bankName"
          label="银行"
          align="center"
          :formatter="formatTd"
          width="175px"
        ></el-table-column>
        <el-table-column
          prop="accountCode"
          label="账号"
          align="center"
          :formatter="formatTd"
          width="225px"
        ></el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          align="center"
          :formatter="formatTd"
        ></el-table-column>
        <el-table-column
          prop="status"
          label="同步状态"
          align="center"
          :formatter="formatTd"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.status == '0'">未同步</span>
            <span v-else>已同步</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          v-if="userType == 'BANK' && bankAcountImport"
          align="center"
          :formatter="formatTd"
          width="200"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-link type="primary" @click="deleteSalary(scope.row)"
              >删除</el-link
            >
            <el-link
              v-if="scope.row.status == '0'"
              type="primary"
              @click="toSyncSalary(scope.row)"
              >手动同步</el-link
            >
          </template>
        </el-table-column>

        <!-- 表格数据为空时，页面显示 -->
        <div slot="empty" v-show="isShow">
          <emptyTable emptyText="暂无数据"></emptyTable>
        </div>
      </el-table>
      <Pagination
        ref="pagination"
        @getList="getTableList"
        :filterField="filterField"
        :requestUrl="requestUrl"
      ></Pagination>
    </div>
    <el-dialog
      title="上传失败"
      :visible.sync="formVisible"
      :close-on-click-modal="false"
      @close="closeDialog"
      custom-class="dialog-minwidth"
      :modal-append-to-body="false"
    >
      <div class="errorNoticeBox">
        <i class="icon iconfont iconshibai1"></i>
      </div>
      <div v-html="errorNotice" class="errorBox"></div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click.native="closeDialog" class="save"
          >确认</el-button
        >
        <el-button @click.native="closeDialog" class="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import operateListTab from '@/components/publicCom/operateListTab'
import common from '../../kits/common'
import moment from 'moment'
export default {
  name: 'newSalarySpecialAccount',
  props: ['projectId', 'accountCode', 'bankId', 'isShowImport', 'projectName'],
  components: {},
  data() {
    return {
      hiddleToolBar: false,
      noAccount: false,
      yesAccount: false,
      loading: true,
      isShow: false, //列表加载
      //表格数据
      salaryAccountList: [],
      requestUrl: 'api-acc/journalmiddle/base/journalmiddlelist',
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
      },
      filterField: {
        time: '',
        accountCode: '',
        bankId: '',
        searchText: '',
        projectId: '',
        operate: '',
      },
      bankName: '', //专户银行
      bankSiteName: '', //银行网点名称
      account: '', //专户账号
      balance: '', //专户余额
      payTotal: '', //专户总缴纳
      expensesTotal: '', //专户总支出
      tipsInfo: '',

      canSync: false, //加载中
      syncAccountBtn: false,
      projectName: '',
      pbName: '',
      uploadContractTwo: false,
      userType: '',
      formVisible: false,
      errorNotice: '',
      flieUpload: {
        projectId: '',
      },
      bankAcountImport: false,
      typeList: [
        {
          name: '缴存',
          id: 'IN',
        },
        {
          name: '支出',
          id: 'OUT',
        },
      ],
      advanced: false,
    }
  },
  created() {
    this.filterField.accountCode = this.accountCode
    this.filterField.bankId = this.bankId
    this.filterField.projectId = this.projectId
    this.userType = this.$store.state.userType
    // this.getAcountInfo();
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
    this.getBankAcountdetail()
    // this.syncAccountBtn = this.$store.state.buttonLimitsArr.indexOf('accountList:add') >-1 || this.$store.state.buttonLimitsArr.indexOf('accountList:update') >-1 ;
  },
  activated() {
    window.addEventListener('scroll', this.handleScroll, true)
    this.$nextTick(function () {
      this.$refs.tableBox1.doLayout()
    })
  },
  deactivated() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  beforeDestroy() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  mounted() {
    if (this.$route.query.projectId) {
      this.flieUpload.projectId = this.$route.query.projectId
    }
    let that = this
    this.$nextTick(function () {
      let tableHeightCur = this.$refs.tableBox1.$el.clientHeight
      let tableTop = this.$refs.tableBox.getBoundingClientRect().top
      if (tableHeightCur + tableTop > window.innerHeight) {
        this.tableHeight =
          this.$refs.mainCon.getBoundingClientRect().height - 290
      } else {
        document.getElementsByClassName('tableBoxCur').length &&
          (document.getElementsByClassName('tableBoxCur')[0].style.height =
            window.innerHeight - tableTop - 328 + 'px')
      }

      window.onresize = function () {
        if (!that.$refs.tableBox1) {
          return
        }
        let tableHeightCur = that.$refs.tableBox1.$el.clientHeight
        let tableTop = that.$refs.tableBox.getBoundingClientRect().top
        if (tableHeightCur + tableTop > window.innerHeight) {
          that.tableHeight =
            that.$refs.mainCon.getBoundingClientRect().height - 300
        } else {
          document.getElementsByClassName('tableBoxCur').length &&
            (document.getElementsByClassName('tableBoxCur')[0].style.height =
              window.innerHeight - tableTop - 40 + 'px')
        }
      }
    })
  },
  methods: {
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    handleScroll(e) {
      this.$nextTick(function () {
        if (
          this.$refs.tableBox &&
          this.$refs.tableBox.getBoundingClientRect().top < 128
        ) {
          // this.tableHeight = this.$refs.mainCon.getBoundingClientRect().height - 84
          this.tableHeight = window.innerHeight - 242

          if (document.getElementsByClassName('tableBoxCur').length) {
            document.getElementsByClassName('tableBoxCur')[0].style.height =
              null
          }
          this.hiddleToolBar = true
        } else {
          this.hiddleToolBar = false
        }
      })
    },
    getTableList(data) {
      this.salaryAccountList = data
      this.loading = false
      if (this.salaryAccountList.length < 1) {
        this.isShow = true
      }
    },
    searchList() {
      this.$refs.pagination.getTableListData()
    },
    format(row, column, cellValue) {
      return moment(cellValue).format('YYYY-MM-DD')
    },
    deleteSalary(row) {
      this.$confirm('是否确认删除此工资专户流水?', '删除工资专户流水', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.toDeleteSalary(row)
        })
        .catch(() => {})
    },
    toDeleteSalary(row) {
      this.axios({
        method: 'post',
        url: 'api-acc/journalmiddle/base/delete',
        data: {
          id: row.id,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.$message({
                message: '删除成功',
                type: 'success',
              })
              this.$refs.pagination.getTableListData()
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    toSyncSalary(row) {
      if (this.isShowImport == 1) {
        this.$message({
          message: '该专户已销户，不可手动同步',
          type: 'warning',
        })
        return
      }
      this.$confirm('是否确认手动同步?', '同步工资专户流水', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.syncSalary(row)
        })
        .catch(() => {})
    },
    syncSalary(row) {
      this.axios({
        method: 'post',
        url: 'api-acc/journalmiddle/base/syncjournal',
        data: {
          id: row.id,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.$message({
                message: response.data.msg,
                type: 'success',
              })
              this.$refs.pagination.getTableListData()
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    //专户流水
    getBankAcountdetail() {
      this.axios({
        method: 'post',
        url: 'api-m/paramconfig/findbyname',
        data: {
          name: 'bankAcountdetail',
        },
      })
        .then((res) => {
          if (!res.data.hasError) {
            if (res.data.result.value == '1') {
              this.bankAcountImport = true
            } else {
              this.bankAcountImport = false
            }
          } else {
            this.$message({
              type: 'error',
              message: response.data.errorMsg,
            })
          }
        })
        .catch((error) => {
          this.$message({
            showClose: true,
            duration: 3000,
            message: '数据请求失败，请重试',
            type: 'error',
          })
        })
    },
    // 流水导入模板下载
    downLoad() {
      this.axios({
        method: 'post',
        url: 'api-su/salary/expand/findurl',
        data: {
          name: 'bankAccount',
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              window.open(response.data.result.url)
            } else {
              this.$message({
                type: 'error',
                message: response.data.msg,
              })
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    // 流水导入 ------start
    waterImportfileChange(e) {
      var that = this
      var url = window.location.href
      var Filedata = $('#waterImportExcel').val()
      var files = e.target.files[0]
      if (!/\.(xls|xlsx)$/.test(Filedata)) {
        this.$message({
          message: 'excel类型必须是.xls,xlsx中的一种',
          type: 'warning',
        })
        return
      }

      setTimeout(function () {
        that.uploadFileByAjaxSubmit(
          'api-acc/journalmiddle/base/import',
          that.success,
          that.error
        )
      }, 500)
    },
    uploadFileByAjaxSubmit(url, successCallBack, errorCallBack) {
      const vm = this
      var token = localStorage.getItem('access_token')
      var options = {
        url: common.uploadUrl + url,
        type: 'POST',
        data: vm.flieUpload,
        headers: { Authorization: 'Bearer ' + token },
        contentType: false,
        processData: false,
        success: function (data) {
          $('#waterImportExcel').val('')
          successCallBack(data)
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          $('#waterImportExcel').val('')
          errorCallBack(XMLHttpRequest, textStatus, errorThrown)
        },
      }

      //三种方式均可
      $('#waterImportBox').ajaxSubmit(options)
      return false
    },
    success(data) {
      if (!data.hasError) {
        this.$message({
          message: data.msg,
          type: 'success',
        })
        this.$nextTick(function () {
          this.$refs.pagination.getTableListData()
        })
      } else {
        this.errorNotice = data.errorMsg
        this.formVisible = true
      }
    },
    //根据状态码判断是否是401
    error(XMLHttpRequest, textStatus, errorThrown) {
      if (XMLHttpRequest.status === '401' || XMLHttpRequest.status === '403') {
        localStorage.setItem('access_token', '')
        localStorage.setItem('refresh_token', '')
        localStorage.setItem('userName', '')
        // 只有在当前路由不是登录页面才跳转
        if (router.currentRoute.path !== '/login/loginFirst') {
          router.replace({
            path: '/login/loginFirst',
          })
        }
        //清除tab栏数据
        this.$store.state.sliderBar = []
        localStorage.removeItem('sliderBar')
      } else {
        this.$message({
          message: '数据请求失败',
          type: 'warning',
        })
      }
    },
    closeDialog() {
      this.formVisible = false
    },
    // 是否导入
    isImport() {
      this.$message({
        message: '该专户已销户，不可导入流水',
        type: 'warning',
      })
    },
    toExport() {
      const vm = this
      if (vm.salaryAccountList.length > 0) {
        window.location.href =
          common.commonApi +
          'api-acc/journalmiddle/base/bankJournalMiddleExport?bankId=' +
          vm.filterField.bankId +
          '&accountCode=' +
          vm.filterField.accountCode +
          '&searchText=' +
          this.filterField.searchText +
          '&projectId=' +
          this.filterField.projectId +
          '&projectName=' +
          encodeURIComponent(vm.projectName) +
          '&time=' +
          vm.filterField.time +
          '&operate=' +
          vm.filterField.operate +
          '&access_token=' +
          localStorage.getItem('access_token')
      } else {
        vm.$message({
          type: 'error',
          message: '无数据导出',
        })
      }
    },
  },
}
</script>
<style lang="less" scoped>
.container {
  .noAccount {
    padding-top: 60px;
    text-align: center;
    color: #666666;
    .noDataInfo {
      margin-top: 16px;
    }
  }
  .accountInfo {
    ul li {
      // width: 415px;
      width: 388px;
      // height: 200px;
      height: 212px;
      float: left;
      padding: 24px 33px;
      border: 1px solid #dee5f4;
      .balace {
        font-size: 24px;
      }
      .color999 {
        font-size: 14px;
      }
      .color333 {
        font-size: 14px;
        line-height: 34px;
      }
      .marTop {
        margin-top: 14px;
      }
      &:first-child {
        background: #f5f7fb;
      }
      &:nth-child(2) {
        border-left: none;
        .botBorder {
          width: 100%;
          height: 1px;
          background: #dee5f4;
          margin: 26px 0;
        }
        .payoff div {
          width: 50%;
          float: left;
        }
      }
      &:nth-child(3) {
        width: 280px;
        border-left: none;
      }
    }
  }
  .runWater {
    margin-top: 32px;
    margin-bottom: 16px;
    font-size: 16px;
    font-weight: bold;
    border-bottom: 1px solid #dee5f4;
    height: 28px;
  }
  // 修改专户弹窗样式
  .uploadBox {
    position: relative;
    .uploadImg {
      width: 96px;
      height: 36px;
      padding: 0px;
      color: #009588;
      border: 1px solid #009588;
      cursor: pointer;
    }
    .upLoadDom {
      position: absolute;
      width: 96px;
      height: 36px;
      top: 0;
      left: 0;
      opacity: 0;
      line-height: 0px;
      form {
        input {
          width: 96px;
          height: 36px;
          line-height: 0px;
          cursor: pointer;
        }
      }
    }
  }
  .AgreementBox {
    /deep/label {
      line-height: 20px;
    }
  }
  .imgStyle {
    margin-left: 135px;
    li {
      position: relative;
      margin-right: 20px;
      margin-bottom: 20px;
      .iconjian {
        position: absolute;
        right: -6px;
        top: -10px;
        font-size: 20px;
        cursor: pointer;
      }
      .el-image {
        cursor: pointer;
      }
    }
  }
  .createSalaryBut {
    background: #009588;
    border: 1px solid #009588;
    padding: 10px 23px;
    margin-left: 12px;
    &:hover {
      opacity: 0.8;
    }
  }
  .errorNoticeBox {
    text-align: center;
    margin-bottom: 24px;
    i {
      color: red;
      font-size: 50px;
    }
  }
  .errorBox {
    line-height: 24px;
  }
  .download {
    position: absolute;
    right: 30px;
    top: 0;
  }
  .previewImg {
    position: absolute;
    top: 0;
    left: 0;
    right: 30px;
    cursor: pointer;
    /deep/.el-image__preview {
      opacity: 0;
    }
  }
  // .addAccount {
  //       padding-top: 24px;
  // }
  // /deep/ .el-dialog__body {
  //   padding: 0;
  // }
}
@import '../../../static/css/filterArea.less';
</style>
